package com.cx.util.device;

import android.widget.Toast;

import com.cx.util.AppUtils;


/**
 * 吐司帮助类，解决吐司多重显示，减少由Toast持有Activity 导致的内存泄漏
 */
public class ToastHelper {
    /**
     * 上一次吐司的内容
     */
    private static String mLastMsg;
    /**
     * 上次显示吐司的时间戳
     */
    private static long mLastTime;

    /**
     * 上一个吐司
     */
    private static Toast mToast;


    public static void showMsg(String msg) {
        showMsg(msg, Toast.LENGTH_SHORT);
    }


    public static void showMsg(String msg, int duration) {
        long currentTime = System.currentTimeMillis();

        if (mToast == null) {
            makeToast(msg, duration);
        } else {

            if (msg.equals(mLastMsg)) {
                if (currentTime - mLastTime > Toast.LENGTH_SHORT) {
                    mToast.show();
                }
            } else {
               makeToast(msg,duration);
            }
        }
        mLastTime = currentTime;
    }


    private static void makeToast(String msg, int duration) {
        mToast = Toast.makeText(AppUtils.getApp(), msg, duration);
        mToast.show();
        mLastMsg = msg;
    }
}
